package com.zwp.base.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.zwp.base.R
import com.zwp.base.state.DefaultStateContainerProcessor
import com.zwp.base.state.IStateContainerProcessor
import com.zwp.base.state.StateModelController
import java.lang.reflect.ParameterizedType


abstract class BaseFragment<V : ViewDataBinding, VM : BaseViewModel> : Fragment() {

    protected lateinit var binding: V
    val viewModel by lazy {
        ViewModelProvider(this).get(getTypeClass())
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewDataBinding()
        //私有的ViewModel与View的契约事件回调逻辑
        registerUiChangeLiveDataCallback()
        initData()
        //一般用于监听viewModel层数据
        initViewObservable()
    }

    /**
     * 注入绑定,绑定缺省页
     */
    private fun initViewDataBinding() {
        binding.setVariable(initVariableId(), viewModel)
        binding.lifecycleOwner = this

        if (needDefaultView()) {
            StateModelController(requireActivity(),
                this,
                useCustomLayout(),
                viewModel.stateModel,
                createStateContainerProcessor())
        }
    }

    /**
     * 缺省页的layout
     */
    protected fun useCustomLayout() = R.layout.base_activity_default

    /**
     * 构建缺省页容器
     */
    fun createStateContainerProcessor(): IStateContainerProcessor {
        val rootView = binding.root
        require(rootView is ConstraintLayout) { "根布局必须为ViewGroup才能添加缺省页" }
        return DefaultStateContainerProcessor(rootView)
    }

    fun needDefaultView() = true

    private fun registerUiChangeLiveDataCallback() {
        viewModel.uc.apply {
            showDialogEvent.observe(this@BaseFragment) {}
            showCancelableDialogEvent.observe(this@BaseFragment) {}
            dismissDialogEvent.observe(this@BaseFragment) {}
            startActivityEvent.observe(this@BaseFragment) {}
            finishEvent.observe(this@BaseFragment) { finish() }
            onBackPressedEvent.observe(this@BaseFragment) { onBackPressed() }
        }
    }

    fun finish() {
        requireActivity().finish()
    }

    fun onBackPressed() {
        requireActivity().onBackPressed()
    }

    fun initViewObservable() {

    }

    fun initData() {

    }

    abstract fun getLayoutId(): Int

    /**
     * viewModel的id，databinding使用
     */
    abstract fun initVariableId(): Int

    fun getTypeClass() =
        javaClass.genericSuperclass!!.let {
            if (it is ParameterizedType) {
                it.actualTypeArguments[0] as Class<VM>
            } else {
                BaseViewModel::class.java as Class<VM>
            }
        }
}